<?php
/**
 * Copyrigh () 2017 湖南魔工坊科技有限公司 版权所有
 * 网址：http://www.mogo.club
 * 项目名称：环球世界交易平台
 * 文件名称：Finance.php
 * 时间：2017年8月25日
 * 作者：
 */

namespace app\world\home;


use app\world\model\Goods as GoodsModel;
use app\world\model\GoodsRuls;
use app\world\model\NewsUser;
use app\world\model\Order;
use app\world\model\User;
use app\world\model\GoodsPrice;
use app\world\model\Configs;

class Goods extends Common
{

    /**
     * 初始化
     * @author
     */
    protected function _initialize()
    {
        parent::_initialize();
        $this->model = new GoodsModel();
    }

    /**
     * 模型
     * @author
     */
    private $model;


    /**
     * 資產列表
     * @author
     */
    public function index()
    {

        $User = new User();
        $id = session('home_user')['id'];
        $user_data = $User->get_find(['id' => $id])->toArray();

        $user_data['sum_money'] = $User->sum_money($user_data['id']);
        $user_data['level'] = $User->sum_level($user_data['id']);
        $Con = new Configs();
        $con = $Con->get_find();

        $user_data['shop_money'] = num_format($con->shop_money);

        $goods = $User->get_list_goods($id);

        if (!$_SESSION['is_language']) {
            foreach ($goods as $k => &$v) {
                $v['name'] = str_replace('比克', 'bike', $v['name']);
            }
        }

       if($user_data['group_id']==2){
            $Goods=new GoodsModel();
            $goods_data=$Goods->get_shareholder_data($id);

            foreach ($goods as $key =>$val){
                if(!empty($goods_data[$val['id']])){
                    @$goods[$key]['total_user_num']=$goods_data[$val['id']]['total_user_num'];
                    @$goods[$key]['total_money']=number_format($goods_data[$val['id']]['total_money'],2);
                    @$goods[$key]['total_sum']=$goods_data[$val['id']]['total_sum'];
                    @$goods[$key]['total_profit_loss']=number_format($goods_data[$val['id']]['total_profit_loss'],2);
                    @$goods[$key]['total_sell_num']=$goods_data[$val['id']]['total_sell_num'];
                    @$goods[$key]['total_pre_sell_num']=$goods_data[$val['id']]['total_pre_sell_num'];
                    @$goods[$key]['total_new_money']=number_format($goods_data[$val['id']]['total_sum']*$val['money'],2);//当前持有总价值

                    @$goods[$key]['zk_total_user_num']=$goods_data[$val['id']]['zk_total_user_num'];
                    @$goods[$key]['zk_total_money']=number_format($goods_data[$val['id']]['zk_total_money'],2);
                    @$goods[$key]['zk_total_sum']=$goods_data[$val['id']]['zk_total_sum'];
                    @$goods[$key]['zk_total_profit_loss']=number_format($goods_data[$val['id']]['zk_total_profit_loss'],2);
                    @$goods[$key]['zk_total_sell_num']=$goods_data[$val['id']]['zk_total_sell_num'];
                    @$goods[$key]['zk_total_pre_sell_num']=$goods_data[$val['id']]['zk_total_pre_sell_num'];
                    @$goods[$key]['zk_total_new_money']=number_format($goods_data[$val['id']]['zk_total_new_money'],2);//当前持有总价值
                }
            }
       }

        $this->assign([
            'goods' => $goods,
            'user_data' => $user_data
        ]);
        return $this->fetch();
    }

    /**
     * 添加資產
     * @author
     */
    public function add()
    {
        if ($this->request->post()) {
            $User = new User();
            $user = $User->get_find(['id' => session('home_user')['id']]);
            if ($user->group_id != 2) echo '非法操作', die;
            $data = input();
            $validate = $this->validate($data, 'Goods.add');
            if ($validate !== true) $this->error($validate);
            $data['user_id'] = $user->id;
            $data['money'] = $data['int_money'];
            $data['benchmark_money'] = $data['int_money'];
            $data['time'] = time();
            $b = $this->model->add_goods($data);
            if ($b) {
                $GoodsRuls = new GoodsRuls();
                $GoodsRuls->goods_id = $b->id;
                $GoodsRuls->money = $b->int_money;
                $GoodsRuls->times = $b->create_time;
                $GoodsRuls->save();
                $this->success(@$_SESSION['is_language'] ? '操作成功' : 'Successful operation', url('index'), '', 1);
            } else {
                $this->error(@$_SESSION['is_language'] ? '操作失敗' : 'Operation failed', url('index'));
            }
        }
        echo '非法操作';
    }


    /**
     * ajax返回資產数据
     * @author
     */
    public function ajax_data()
    {
        if ($this->request->post()) {
            $data = input();
            if (isset($data['type'])) { //修改
                $User = new User();
                $user = $User->get_find(['id' => session('home_user')['id']]);
                if ($user->group_id != 2) echo '非法操作', die;
            }
            $goods = $this->model->get_find(['id' => $data['id']])->toArray();
            $con = new Configs();
            $con_data = $con->get_find('purchase_fee,sell_fee');
            $data['goods'] = $goods;
            $data['con']['purchase_fee'] = $con_data->purchase_fee;
            $data['con']['sell_fee'] = $con_data->sell_fee;
            if ($goods) {
                return ['code' => 1, 'msg' => '', 'content' => $data];
            } else {
                return ['code' => 0, 'msg' => @$_SESSION['is_language'] ? '資產不存在' : 'Non-existent', 'content' => ''];
            }
        }
        echo '非法操作';
    }


    /**
     * ajax返回資產数据
     * @author
     */
    public function ajax_order()
    {
        if ($this->request->post()) {
            $data = input();
            if (!isset($data['id'])) return ['code' => 0, 'msg' => '', 'content' => @$_SESSION['is_language'] ? '參數不全' : 'Incomplete parameter'];
            $Order = new Order();
            $info = $Order->get_find(['world_order.id' => $data['id']])->toArray();
            if ($info) {
                return ['code' => 1, 'msg' => '', 'content' => $info];
            } else {
                return ['code' => 0, 'msg' => @$_SESSION['is_language'] ? '資產不存在' : 'Non-existent', 'content' => ''];
            }
        }
        echo '非法操作';

    }


//    /**
//     * 购买資產
//     * @author
//     */
//    public function order()
//    {
//        if ($this->request->post()) {
//            $User = new User();
//            $Order = new Order();
//            $NewsUser = new NewsUser();
//            $id = session('home_user')['id'];
//            $user = $User->get_find(['id' => $id]);
//            $data = input();
//            if ($data['sum'] < 1) $this->error('資產数量不正确');
//            $goods = $this->model->get_find(['id' => $data['id']]);
//            if ($goods->sum < $data['sum']) $this->error('資產数量不足,无法匹配');
//            $money = $data['sum'] * $goods->money;
//            if ($user->money1 < $money) $this->error('您的余额不足,无法匹配');
//            $user->money1 -= $money;
//            $b = $user->save();
//            if ($b) {
//                $info['type'] = 1;
//                $info['pid'] = $goods->user_id;
//                $info['user_id'] = session('home_user')['id'];
//                $info['goods_id'] = $goods->id;
//                $info['money'] = $goods->money;
//                $info['sum'] = $data['sum'];
//                $Order->add_order($info);
//                $NewsUser->user_id = $id;
//                $NewsUser->title = '兑入資產消息';
//                $NewsUser->content = '您购买的資產正在匹配卖家,请耐心等待';
//                $NewsUser->save();
//                $this->success('正在匹配卖家,请等待');
//            } else {
//                $this->error('操作失败');
//            }
//        }
//        echo '非法操作';
//    }


    /**
     * 购买資產
     * @author
     */
    public function order()
    {
        if ($this->request->post()) {
            $User = new User();
            $Order = new Order();
            $NewsUser = new NewsUser();
            $id = session('home_user')['id'];
            $user = $User->get_find(['id' => $id]);
            $data = input();
            if(!empty($data['buy_type'])&&$data['buy_type']==2){//做空消息提示修改
                $msg='您的做空合約資產已經申請，請等待審核';
                $msg1='Your short contract assets have been applied. Please wait for the audit';
//                    $NewsUser->content = '您的做空合約資產已經生效，請等待審核。Your short contract assets have entered into force. Please wait for the audit';
                $msg2='申請做空';
            }else{
                $msg= '您購買的資產正在匹配資產賣家';
                $msg1= 'The assets you buy are matching the asset seller';
//                    $NewsUser->content = '您購買的資產正在匹配資產賣家。The assets you buy are matching the asset seller';
                $msg2='購買資產';
            }
            if ($data['sum'] < 1) return ['code' => 0, 'msg' => @$_SESSION['is_language'] ? '資產數量不正確' : 'Wrong number', 'msg1' => 'Parameter error', 'content' => ''];
            $goods = $this->model->get_find(['id' => $data['id']]);
//            if ($goods->sum < $data['sum']) $this->error('資產数量不足,无法匹配');
            $con = new Configs();
            $con_data = $con->get_find('purchase_fee,sell_fee');
            $goods_money = $data['sum'] * $goods->money;
            $fee_money = $goods_money * $con_data['purchase_fee'];
            $money = $goods_money + $fee_money;
            if ($user->money1 < $money) return ['code' => 0, 'msg' => '餘額不足', 'msg1' => 'Sorry, your credit is running low', 'content' => ''];
            $user->money1 -= $money;
            $b = $user->save();
            if ($b) {
                User::money_change($user->id, 0, $money, $msg2 . $goods->name . '’ Purchase of assets');
                $info['type'] = 1;
                $info['pid'] = $goods->user_id;
                $info['user_id'] = session('home_user')['id'];
                $info['goods_id'] = $goods->id;
                $info['money'] = $goods->money;
                $info['sum'] = $data['sum'];
                $info['buy_type']=!empty($data['buy_type'])?$data['buy_type']:1;
                $info['purchase_fee'] = $con_data['purchase_fee'];
                $list = $Order->add_order($info);
                $NewsUser->user_id = $id;
                $NewsUser->title = '資產消息。Asset message';

                $NewsUser->content =$msg.'。'.$msg1;
                $NewsUser->save();
                if ($goods->user_id == 0) {
                    //修改订单状态
                    $list->status = 2;
                    $list->save();
                    //发送消息
                    $NewsUser = new NewsUser();
                    $NewsUser->user_id = $id;
                    $NewsUser->title = '資產消息。Asset message';
                    $NewsUser->content = '您購買的資產匹配失敗,您可以重新匹配或購買其他資產。The asset match you purchased failed, and you can match or buy other assets';
                    $NewsUser->save();
                    //修改用户金额
                    $users = User::get($id);
                    $users->money1 += $money;
                    User::money_change($user->id, 0, $money, '購買‘' . $goods->name . '’資產失敗 Failure to buy assets');
                    $users->save();
                }
//                return ['code' => 1, 'msg' => '您購買的資產正在匹配資產賣家', 'msg1' => 'The assets you buy are matching the asset seller', 'content' => ''];
                return ['code'=> 1, 'msg' => $msg,'msg1' => $msg1, 'content' => ''];
            } else {
                return ['code' => 0, 'msg' => '操作失敗', 'msg1' => 'operation failed', 'content' => ''];
            }
        }
        return ['code' => 0, 'msg' => '非法操作', 'msg1' => 'Illegal operation', 'content' => ''];
    }


    /**
     * 修改資產
     * @author
     */
    public function edit()
    {
        if ($this->request->post()) {
            $data = input();
            $validate = $this->validate($data, 'goods.edit');
            if ($validate !== true) $this->error($validate);
            $User = new User();
            $user = $User->get_find(['id' => session('home_user')['id']]);
            if ($user->group_id != 2) echo '非法操作', die;
            $b = $this->model->edit_goods($data);
            if ($b) {
                $this->success(@$_SESSION['is_language'] ? '操作成功' : 'Successful operation', url('index'), '', 1);
            } else {
                $this->error(@$_SESSION['is_language'] ? '操作失敗' : 'Operation failed', url('index'), '', 1);
            }
        }
        echo '非法操作';
    }


    /**
     * 买入申请列表
     * @author
     */
    public function buyin()
    {

        if (session('home_user')['group_id'] != 2) $this->error(@$_SESSION['is_language'] ? '沒有權限' : 'No permission');
        $id = input('id');
        $buy_type = request()->only('buy_type');

        $map=['status' => ['in', [0, 1, 2, 3, 4, 5]], 'goods_id' => $id, 'type' => ['in', [1, 4]], 'pid' => session('home_user')['id']];

        if(!empty($buy_type)&&$buy_type['buy_type']==2){
            $map['buy_type']=['eq',2];
        }else{
            $map['buy_type']=['neq',2];
        }

        if (!$id) $this->error(@$_SESSION['is_language'] ? '缺少參數' : 'Missing parameters');
        $Order = new Order();
        $User = new User();

        $order_data = $Order->get_select($map, 'status,id desc', 15);

        $page = $order_data->render();
        $order_data = $order_data->toArray();

        foreach ($order_data['data'] as &$v) {
            $v['user'] = $User->get_find(['id' => $v['user_id']])->toArray();
        }

        $this->assign([
            'order_data' => $order_data,
            'page' => $page,
            'buy_type' => @$buy_type['buy_type']?$buy_type['buy_type']:0
        ]);

        return $this->fetch();
    }


    /**
     * 同意买入or拒绝买入处理
     * @author
     */
    public function buyin_info()
    {

        if ($this->request->post()) {
            if (session('home_user')['group_id'] != 2) $this->error(@$_SESSION['is_language'] ? '沒有權限' : 'No permission');
            $data = input();
            if (!$data) $this->redirect('index');
            $Order = new Order();
            $User = new User();
            $NewsUser = new NewsUser();
            $info = $Order::with('goods')->where(['id' => $data['id']])->find();
            if (!$info->id) $this->error(@$_SESSION['is_language'] ? '資產不存在' : 'Non-existent');
            if ($info->status != 0) $this->error(@$_SESSION['is_language'] ? '参数错误' : 'Missing parameters');

            if ($data['sum'] > $info->sum) $this->error(@$_SESSION['is_language'] ? '數量超標' : 'Outnumber');
            if(!empty($info['buy_type'])&&$info['buy_type']==2) {
                $remark='做空合約資產';
            }else{
                $remark='資產';
            }
            $goods_money = ($info->sum - $data['sum']) * $info->money;
            $fee_money = ($info->sum - $data['sum']) * $info->money * $info['purchase_fee'];
            $user = User::get($info->user_id);//购买资产的用户

            if ($info->is_capital && $info->type == 4 && $info->status == 0) {   //配资
                $t_user = User::find($info->transfer_id);
                if ($data['type'] == 'agree') { //同意
                    $info->status = 1;
                    $User->get_commission($info->user_id, $data['sum'] * $info->money, $info->id, $user->is_brokers);//佣金
                    $content = '您購買的配資資產匹配成功,請前往配资资产查看。The matching assets you bought have been matched successfully. Please go to the assets to check the assets.';
                    $content1 = '您配資的資產匹配成功,請前往我的配資查看。Your matching assets are successful, please go to my allocation';
                    $time = time();
                    $chang1 = '返還由配資商‘' . $t_user->username . '’配資的‘' . $info->goods->name . '’資產剩余的金額 Return amount';
                    $chang2 = '返還由融资人‘' . $user->username . '’融资的‘' . $info->goods->name . '’資產剩余的金額 Return amount';
                }
                if ($data['type'] == 'refuse') { //拒绝
                    $info->status = 2;
                    $data['sum'] = 0;
                    $content = '您購買的配資資產匹配失敗,您可以重新匹配或購買其他資產。The matching assets you purchased failed, and you could re match or buy other assets.';
                    $content1 = '您配資的資產匹配失敗,請前往我的配資查看。Your matching assets fail, please go to my allocation';
                    $time = 0;
                    $chang1 = '配資商‘' . $t_user->username . '’配資的‘' . $info->goods->name . '’資產匹配失敗 Match failure';
                    $chang2 = '融资人‘' . $user->username . '’融资的‘' . $info->goods->name . '’資產匹配失敗 Match failure';
                }


                //修改订单记录
                $selling_money = round($data['sum'] * $info->money * $info->capital_pro / ($info->capital_pro + 1), 2);
                $info->actual_sum = $data['sum'];
                $info->surplus_sum = $data['sum'];
                $info->time = $time;
                $info->selling_money = ($info->selling * $data['sum'] * $info->money) * 0.01 + $selling_money;
                $info->margin_money = ($info->margin * $data['sum'] * $info->money) * 0.01 + $selling_money;
                $info->save();

                $user_money = $goods_money / (1 + $info->capital_pro) + $fee_money;
                //修改用户金额
                $user->money1 += round($user_money, 2);
                $user->save();


                //修改融资商金额
                $capital_user = User::get($info->transfer_id);
                $capital_user->money1 += round($goods_money * $info->capital_pro / (1 + $info->capital_pro), 2);
                $capital_user->save();
                if ($user_money) { //配资
                    User::money_change($user->id, 1, round($user_money, 2), $chang1);
                    User::money_change($capital_user->id, 1, round($goods_money * $info->capital_pro / (1 + $info->capital_pro), 2), $chang2);
                }

                //修改股东金额
                $p_user = User::get($info->pid);
                //$p_user->money1 += $data['sum'] * $info->money;
                $p_user->money4 += $data['sum'] * $info->money;
                $p_user->save();


                //发送消息
                $NewsUser->user_id = $info->user_id;
                $NewsUser->title = '資產配資消息。Asset financing message';
                $NewsUser->content = $content;
                $NewsUser->save();


                //发送消息
                $NewsUser1 = new NewsUser();
                $NewsUser1->user_id = $info->transfer_id;
                $NewsUser1->title = '資產配資消息。Asset financing message';
                $NewsUser1->content = $content1;
                $NewsUser1->save();

                $this->success(@$_SESSION['is_language'] ? '操作成功' : 'Successful operation', url('index'), '', 1);
            } else if ($info->is_capital == 0 && $info->type == 1 && $info->status == 0) { //全资购买
                $goods_money = ($info->sum - $data['sum']) * $info->money;
                $fee_money = ($info->sum - $data['sum']) * $info->money * $info->purchase_fee;
                $money = $goods_money + $fee_money;
                //$sum = $info->goods->sum - $data['sum'];

                if ($data['type'] == 'agree') {
                    $info->status = 1;   //同意
                    $User->get_commission($info->user_id, $data['sum'] * $info->money, $info->id, $user->is_brokers);//佣金
                    $content = '您購買的'.$remark.'匹配成功,請前往我的資產查看。The assets you purchased match successfully, please go to my asset view';
                }
                if ($data['type'] == 'refuse') {
                    $info->status = 2;  //拒绝
                    $data['sum'] = 0;
                    $content = '您購買的'.$remark.'匹配失敗,您可以重新匹配或購買其他資產。The asset match you purchased failed, and you can match or buy other assets';
                }

                //修改資產库存
                //$info->goods->sum = $sum;
                //$info->goods->save();

                //修改订单记录
                $info->actual_sum = $data['sum'];
                $info->surplus_sum = $data['sum'];
                $info->save();

                //修改用户金额

                $user->money1 += $money;
                $user->save();

                //修改股东金额
                $p_user = User::get($info->pid);
                //$p_user->money1 += $data['sum'] * $info->money;
                $p_user->money4 += $data['sum'] * $info->money;
                $p_user->save();

                //发送消息
                $NewsUser->user_id = $info->user_id;
                $NewsUser->title = $remark.'消息。Asset message';
                $NewsUser->content = $content;
                $NewsUser->save();
                if ($money) {
                    User::money_change($user->id, 1, $money, '返還購買'.$remark.'‘' . $info->goods->name . '’金額 Return the purchase of assets');
                }
                $this->success(@$_SESSION['is_language'] ? '操作成功' : 'Successful operation', url('index'), '', 1);
            }
        }
    }


    /**
     * 卖出申请列表
     * @author
     */
    public function sell()
    {
        if (session('home_user')['group_id'] != 2) $this->error(@$_SESSION['is_language'] ? '沒有權限' : 'No permission');
        $id = input('id');
        $data=request()->only('buy_type');
        if (!$id) $this->error(@$_SESSION['is_language'] ? '缺少參數' : 'Missing parameters');
        $map=['status' => ['in', [0, 1, 2, 3, 4, 5]], 'goods_id' => $id, 'type' => ['in', [2, 5]], 'pid' => session('home_user')['id']];

        if(!empty($data)&&$data['buy_type']==2){
            $map['buy_type']=['eq',2];
        }else{
            $map['buy_type']=['neq',2];
        }
        $Order = new Order();
        $User = new User();

        $order_data = $Order->get_select($map, 'status,id desc', 15);

        $page = $order_data->render();


        $order_data = $order_data->toArray();



        foreach ($order_data['data'] as &$v) {

            $v['user'] = $User->get_find(['id' => $v['user_id']])->toArray();

            if($v['buy_type']==2){
                $v['yingkui']=number_format(($v['money']-$v['money2'])*$v['surplus_sum'],2);
            }else{
                $v['yingkui']=number_format(($v['money2']-$v['money'])*$v['surplus_sum'],2);
            }
        }

        $this->assign([
            'order_data' => $order_data,
            'page' => $page,
            'buy_type' => @$data['buy_type']
        ]);

        return $this->fetch();
    }


    /**
     * 同意卖出or拒绝卖出处理 user 用户  userP股东
     * @author
     */
    public function sell_info()
    {
        if ($this->request->post()) {
            if (session('home_user')['group_id'] != 2) $this->error(@$_SESSION['is_language'] ? '沒有權限' : 'No permission');
            $data = input();
            if (!isset($data['id']) || !isset($data['type']) || !isset($data['sum'])) $this->error(@$_SESSION['is_language'] ? '缺少參數' : 'Missing parameters');
            $Order = new Order();
            $NewsUser = new NewsUser();
            $order_data = $Order->get_find_relation(['id' => $data['id']]);
            if(!empty($order_data['buy_type'])&&$order_data['buy_type']==2) {
                //?'':''
                $remark='做空合約資產';
                $remark1='平倉做空合約資產';
            }else{
                $remark='資產';
                $remark1='賣出資產';
            }

            if ($order_data->is_capital && $order_data->type == 5 && $order_data->status == 0) { //配资卖出
                if ($data['type'] == 'agree') {  //同意配资卖出
                    //配资商投入的钱
                    $user_loan_money = round($order_data->money * $order_data->actual_sum * $order_data->capital_pro / ($order_data->capital_pro + 1), 2);
                    //融资人投入的钱
                    $user_financing_money = $order_data->money * $order_data->actual_sum - $user_loan_money + round(($order_data->money * $order_data->actual_sum * $order_data->purchase_fee), 2) + $order_data->money3;

                    if ($order_data->is_selling) { //平仓
                        if ($order_data->is_automatic) {  //自动平仓
                            if ($order_data->userP->money4 < $order_data->money2 * $data['sum']) {
                                $difference = $order_data->money2 * $data['sum'] - $order_data->userP->money4;
                                $this->error(@$_SESSION['is_language'] ? '資產餘額不足,还需转换' . $difference . '资产余额' : 'The balance of the assets is insufficient and the balance of ' . $difference . ' assets must be converted');
                            }
                            //减去股东资产余额
                            $order_data->userP->money4 -= $order_data->money2 * $data['sum'];
                            $order_data->userP->save();

                            //平仓钱给融资商
                            $money = $order_data->selling_money;

                            //修改订单状态
                            $order_data->status = 1;
                            $order_data->end_time = time();
                            $order_data->user_money = -$user_financing_money;//融资人实际收益
                            $order_data->financing_money = $money - $user_loan_money;   //配资商实际收益
                            $order_data->save();
                            $order_data->order->end_time = time();
                            $order_data->order->save();

                            $chang = '融資人‘'.$order_data->user->username.'’融資的資產‘'.$order_data->goods->name.'’平仓 Asset warehouse';
                            //配资商加钱
                            db('world_user')->where('id', $order_data->transfer_id)->setInc('money1', $money);
                            User::money_change($order_data->transfer_id, 1, $money, $chang);

                            NewsUser::create([
                                'title' => '資產配資。Asset financing',
                                'content' => '您的配資資產已平仓,請前往配資資產查看。Your assets have been closed, please go to the assets to check the assets。',
                                'user_id' => $order_data->user_id,
                            ]);

                            NewsUser::create([
                                'title' => '資產配資。Asset financing',
                                'content' => '您的配資資產已平仓,詳情請查看記錄。Your assets have been closed. For details, please check the record.',
                                'user_id' => $order_data->transfer_id,
                            ]);
                            $this->success(@$_SESSION['is_language'] ? '操作成功' : 'Successful operation', url('index'), '', 1);
                        } else {  //手动平仓
                            if ($order_data->userP->money4 < $order_data->money2 * $data['sum']) {
                                $difference = $order_data->money2 * $data['sum'] - $order_data->userP->money4;
                                $this->error(@$_SESSION['is_language'] ? '資產餘額不足,还需转换' . $difference . '资产余额' : 'The balance of the assets is insufficient and the balance of ' . $difference . ' assets must be converted');
                            }
                            //减去股东资产余额
                            $order_data->userP->money4 -= $order_data->money2 * $data['sum'];
                            $order_data->userP->save();


                            //平仓钱给配资商
                            $money = $order_data->money2 * $data['sum'] + $order_data->money3;

                            //修改订单状态
                            $order_data->status = 1;
                            $order_data->end_time = time();

                            $order_data->user_money = -$user_financing_money;//融资人实际收益
                            $order_data->financing_money = $money - $user_loan_money;   //配资商实际收益


                            $order_data->save();
                            $order_data->order->end_time = time();
                            $order_data->order->save();

                            //配资商加钱
                            db('world_user')->where('id', $order_data->transfer_id)->setInc('money1', $money);
                            $chang = '融資人‘'.$order_data->user->username.'’融資的資產‘'.$order_data->goods->name.'’平仓 Asset warehouse';
                            User::money_change($order_data->transfer_id, 1, $money, $chang);
                            NewsUser::create([
                                'title' => '資產配資。Asset financing',
                                'content' => '您的配資資產已平仓,請前往配資資產查看。Your assets have been closed, please go to the assets to check the assets。',
                                'user_id' => $order_data->user_id,
                            ]);

                            NewsUser::create([
                                'title' => '資產配資。Asset financing',
                                'content' => '您的配資資產已平仓,詳情請查看記錄。Your assets have been closed. For details, please check the record.',
                                'user_id' => $order_data->transfer_id,
                            ]);
                            $this->success(@$_SESSION['is_language'] ? '操作成功' : 'Successful operation', url('index'), '', 1);

                        }
                    } else {  //非平仓

                        if ($order_data->userP->money4 < $order_data->money2 * $data['sum']) {
                            $difference = $order_data->money2 * $data['sum'] - $order_data->userP->money4;
                            $this->error(@$_SESSION['is_language'] ? '資產餘額不足,还需转换' . $difference . '资产余额' : 'The balance of the assets is insufficient and the balance of ' . $difference . ' assets must be converted');
                        }

                        //减去股东资产余额
                        $order_data->userP->money4 -= $order_data->money2 * $data['sum'];
                        $order_data->userP->save();

                        //修改订单状态
                        $order_data->status = 1;
                        $order_data->end_time = time();
                        //$order_data->save();         //利息没计算
                        $order_data->order->end_time = time();
                        //$order_data->order->save();  //利息没计算

                        //计算融资商金额
                        $money = $order_data->money2 * $data['sum'] + $order_data->money3;//所得总金额
                        $capital_mone = 0;
                        //融资金额
                        $order_capital_money = $user_loan_money;
                        if ($money >= $order_capital_money) {
                            $capital_mone = $order_capital_money;
                            $money -= $order_capital_money;
                        } else {
                            $capital_mone = $money;
                            $money = 0;
                        }


                        //手续费
                        $fee_money = $order_data->sell_fee * $order_data->money2 * $order_data->actual_sum;
                        if ($money >= $fee_money) {
                            $money -= $fee_money;
                        } else {
                            $money = 0;
                        }


                        //利息
                        $z_time = $order_data->time;
                        $time = floor((time() - $z_time) / 84600) + 1;
                        $interest = round($order_capital_money * $order_data->capital_interest * $time, 2);
                        if ($money >= $interest) {
                            $real_interest = $interest;  //利息
                            $capital_mone += $interest;
                            $money -= $interest;
                        } else {
                            $real_interest = $money;  //利息
                            $capital_mone += $money;
                            $money = 0;
                        }
                        //保存利息
                        $order_data->capital_money = $real_interest;

                        $order_data->user_money = $money - $user_financing_money;//融资人实际收益
                        $order_data->financing_money = $capital_mone - $user_loan_money;   //配资商实际收益


                        $order_data->save();
                        $order_data->order->capital_money = $real_interest;
                        $order_data->order->save();


                        db('world_user')->where('id', $order_data->transfer_id)->setInc('money1', $capital_mone);
                        db('world_user')->where('id', $order_data->user_id)->setInc('money1', $money);

                        $chang = '融資人‘'.$order_data->user->username.'’融資的資產‘'.$order_data->goods->name.'’賣出 Sell assets';
                        User::money_change($order_data->transfer_id, 1, $capital_mone, $chang);
                        if ($money) {
                            $t_user = User::find($order_data->transfer_id);
                            $chang = '配資商‘'.$t_user->username.'’配資的資產‘'.$order_data->goods->name.'’賣出 Sell assets';
                            User::money_change($order_data->user_id, 1, $money, $chang);
                        }


                        NewsUser::create([
                            'title' => '資產配資。Asset financing',
                            'content' => '您的配資資產已售出,請前往配資資產查看。Your assets have been sold out, please go to the assets to check the assets.',
                            'user_id' => $order_data->user_id,
                        ]);

                        NewsUser::create([
                            'title' => '資產配資。Asset financing',
                            'content' => '您的配資資產已售出,詳情請查看記錄。Your assets have been sold. For details, please check the record.',
                            'user_id' => $order_data->transfer_id,
                        ]);


                        $this->success(@$_SESSION['is_language'] ? '操作成功' : 'Successful operation', url('index'), '', 1);

                    }
                } elseif ($data['type'] == 'refuse') { //拒绝配资卖出
                    $order_data->status = 2;
                    $order_data->save();
                    $order_data->order->surplus_sum += $order_data->surplus_sum;
                    $order_data->order->save();

                    NewsUser::create([
                        'title' => '資產配資。Asset financing',
                        'content' => '您的配資資產平仓失敗,請前往配資資產查看。Your assets have failed, please go to the assets to check the assets. ',
                        'user_id' => $order_data->user_id,
                    ]);

                    NewsUser::create([
                        'title' => '資產配資。Asset financing',
                        'content' => '您的配資資產平仓失敗,詳情請查看記錄。If your assets have failed, please check the record for details.',
                        'user_id' => $order_data->transfer_id,
                    ]);
                    $this->success(@$_SESSION['is_language'] ? '操作成功' : 'Successful operation', url('index'), '', 1);
                }
            } elseif ($order_data->is_capital == 0 && $order_data->type == 2 && $order_data->status == 0) {  //全资卖出
                if ($data['type'] == 'agree') {  //同意全资卖出

                    //if ($order_data->userP->money1 < $order_data->money2 * $data['sum']) $this->error(@$_SESSION['is_language'] ? '餘額不足' : 'Sorry, your credit is running low');
                    if ($order_data->userP->money4 < $order_data->money2 * $data['sum']) {
                        $difference = $order_data->money2 * $data['sum'] - $order_data->userP->money4;
                        $this->error(@$_SESSION['is_language'] ? '資產餘額不足,还需转换' . $difference . '资产余额' : 'The balance of the assets is insufficient and the balance of ' . $difference . ' assets must be converted');
                    }
//                    //新增代码  做空(即买亏)
//                    if($order_data->buy_type==2){//如果是买亏的话   卖出价格应为 买入价格 加上 卖出价格与买入价格的差价
//
//                        $order_data->money2=$order_data->money+($order_data->money-$order_data->money2);
//                    }

                    $a = ($order_data->money2 * $data['sum'] - round($order_data->money2 * $data['sum'] * $order_data->sell_fee, 2)); //减去手续费
                    $order_data->user->money1 += $a;//给用户余额加钱
                    $order_data->user->save();
                    //$order_data->userP->money1 -= $order_data->money2 * $data['sum'];
                    $order_data->userP->money4 -= $order_data->money2 * $data['sum'];//股东减去资产(因为用户购买资产的时候，股东增加的不是余额 是资产)
                    $order_data->userP->save();
                    $order_data->status = 1;
                    $order_data->save();
                    $NewsUser->title = $remark.'消息。Asset message';
                    $NewsUser->content = '您的買入'.$remark.'成功匹配交易會員,請前往資產提現記錄查看。Your buying assets successfully match the trading members, please go to the assets out of record view';
                    $NewsUser->user_id = $order_data->user_id;
                    $NewsUser->save();

                    User::money_change($order_data->user->id, 1, $a, $remark1.'‘'.$order_data->goods->name.'’ Sell assets');
                    $this->success(@$_SESSION['is_language'] ? '操作成功' : 'Successful operation', url('index'), '', 1);
                } elseif ($data['type'] == 'refuse') { //拒绝全资卖出

                    $order_data->status = 2;
                    $order_data->save();
                    $order_data->order->surplus_sum += $order_data->surplus_sum;
                    $order_data->order->save();
                    $NewsUser->title = $remark1.'消息。Sell asset message';
                    $NewsUser->content = '您的'.$remark1.'申請匹配交易會員失敗,如需再次提現請重新發起申請,請前往資產提現記錄查看。If you sell your application for matching transaction, the member fails. If you need to re - issue it, please re - apply for it. Please go to the assets to record the record';
                    $NewsUser->user_id = $order_data->user_id;
                    $NewsUser->save();
                    $this->success(@$_SESSION['is_language'] ? '操作成功' : 'Successful operation', url('index'), '', 1);
                }

            }
        }
    }


    /**
     * 資產详情
     * @author
     */
    public function main()
    {
        $id = input('id');
        if (!$id) $this->error(@$_SESSION['is_language'] ? '缺少參數' : 'Missing parameters');
        $GoodsModel = new GoodsModel();
        $data = $GoodsModel->get_find(['id' => $id]);
        if (!$data) $this->error(@$_SESSION['is_language'] ? '缺少參數' : 'Missing parameters');
        $history = $GoodsModel->get_history($id);
        if(!isset($history['minimum'])){
            $history['minimum'] = $data['int_money'];
        }

        if (!$_SESSION['is_language']) {
            $data->name = str_replace('比克', 'bike', $data->name);
        }

        if (@$history['highest'] < @$history['minimum']) {
            $historys['minimum'] = @$history['highest'];
            $historys['highest'] = @$history['minimum'];
            $historys['average'] = @$history['average'];
        } else {
            $historys = $history;
        }


        $this->assign([
            'data' => $data,
            'history' => $historys
        ]);
        return $this->fetch();
    }

    /**
     * 資產详情-价格ajax请求
     * @author
     */
    public function main_ajax()
    {
        $goods_id = input('id');
        if (!$goods_id) return ['code' => 0, 'msg' => @$_SESSION['is_language'] ? '缺少參數' : 'Missing parameters', 'content' => ''];
        input('type') ? $type = input('type') : $type = 'day';
        $GoodsModel = new GoodsModel();
        $data = $GoodsModel->get_main($goods_id, $type);

        foreach (@(array)$data as $k => &$v) {
            $data[$k]['time'] = date('Y/m/d H:i', $v['end_time']);
        }
        $info = GoodsModel::get($goods_id);
        $data[0]['time'] = date('Y/m/d H:i', $info->create_time);
        return ['code' => 1, 'msg' => '', 'content' => $data];
    }


    /**
     * 資產价格节点
     * @author
     */
    public function set_goods_ruls()
    {
        $id = input('id');
        if (!$id) $this->error(@$_SESSION['is_language'] ? '缺少參數' : 'Missing parameters');
        $GoodsModel = new GoodsModel();
        $data = $GoodsModel->get_goods_ruls(['id' => $id], 'times desc');
        if ($this->request->post()) {
            $info = input('post.');
            $validate = $this->validate($info, 'GoodsRuls.home_add');
            if ($validate !== true) $this->error($validate);
            $GoodsRuls = new GoodsRuls();
            $info['times'] = strtotime($info['times']);
            if ($GoodsRuls->add_goods_ruls($info)) {
                $this->success(@$_SESSION['is_language'] ? '操作成功' : 'Successful operation', '', '', 1);
            } else {
                $this->error(@$_SESSION['is_language'] ? '操作失敗' : 'Operation failed');
            }
        }
        $this->assign([
            'data' => $data,
            'id' => $id
        ]);
        return $this->fetch();
    }


//    /**
//     * 删除价格节点
//     * @author
//     */
//    public function del_goods_ruls()
//    {
//        $id = input('id');
//        if (!$id) $this->error('參數不全');
//        $GoodsRuls = new GoodsRuls();
//        if ($GoodsRuls->del($id)) {
//            return ['code' => 1, 'msg' => '操作成功', 'content' => ''];
//        } else {
//            return ['code' => 0, 'msg' => '操作失敗', 'content' => ''];
//        }
//    }
    public function test(){
//        $a= 3857.99
        $qa=get_rand(4037.99-180.00,4037.99+180.00);
        echo $qa;die;
    }

}